package Demo03.Demo01;

class Clerk{
 
    private int produntCount = 0;
 
    //生产产品
    public synchronized void produceProduct() {
 
        if (produntCount < 20){
            produntCount++;
            System.out.println(Thread.currentThread().getName() + "：开始生产第"+ produntCount +"个产品");
 
            notify();
 
        }else{
 
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
 
        }
 
    }
 
    //消费产品
    public synchronized void consumeProduct() {
 
        if (produntCount > 0){
            System.out.println(Thread.currentThread().getName() + "开始消费第" + produntCount +"个产品");
            produntCount--;
 
            notify();
 
        }else{
 
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
 
        }
 
 
    }
}
 
class Producer extends Thread{//生产者
 
    private Clerk clerk;
 
    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }
 
    @Override
    public void run() {
        System.out.println(getName() + ":开始生产产品....");
        while (true){
 
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
 
            clerk.produceProduct();
        }
 
    }
}
 
class Consumer extends Thread{//消费者
    private Clerk clerk;
 
    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }
 
    @Override
    public void run() {
        System.out.println(getName() + ":开始消费产品....");
        while (true){
 
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.consumeProduct();
        }
    }
}
 
 
public class ProductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk();
 
        Producer p1 = new Producer(clerk);
        p1.setName("喜洋洋");
 
        Consumer c1 = new Consumer(clerk);
        c1.setName("懒洋洋");
 
        Consumer c2 = new Consumer(clerk);
        c2.setName("沸羊羊");
 
        p1.start();
        c1.start();
        c2.start();
    }
 
}